package com.tangmu.rabbits.base;


import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.tangmu.rabbits.R;
import com.tangmu.rabbits.app.AppManager;
import com.tangmu.rabbits.constants.Constants;
import com.tangmu.rabbits.util.MyToast;
import com.tangmu.rabbits.util.StatusBarSetting;
import com.tangmu.rabbits.util.ToastUitl;
import com.tangmu.rabbits.widget.LoadingDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 基类
 */

public abstract class BaseActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {

    public Context mContext;
    private Unbinder mUnbinder;
    private View headerView;//头
    private int count;//记录开启进度条的情况 只能开一个
    //
    private Map<Integer, PermissionCallback> mPermissonCallbacks = null;
    private Map<Integer, String[]> mPermissions = null;

    private InputMethodManager imm;
    protected ImmersionBar mImmersionBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        doBeforeSetcontentView();
        setContentView(getLayoutId());
        // 默认着色状态栏
        //SetStatusBarColor();
        //StatusBarSetting.setColorNoTranslucent(this, getResources().getColor(R.color.colorPrimary));
        mUnbinder = ButterKnife.bind(this);
        mContext = this;
        headerView = findViewById(R.id.headerView);

        this.initPresenter();
        this.initView();
        if (isImmersionBarEnabled())
            initImmersionBar();
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.navigationBarColor(R.color.navigation_color).init();
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.imm == null) {
            this.imm = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.imm != null)) {
            this.imm.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }

    /**
     * 设置layout前配置
     */
    private void doBeforeSetcontentView() {
        // 把actvity放到application栈中管理
        AppManager.getAppManager().addActivity(this);
        // 无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 设置竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }


    /*********************
     * 子类实现
     *****************************/
    //获取布局文件
    protected abstract int getLayoutId();

    //简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
    protected abstract void initPresenter();

    //初始化view
    protected abstract void initView();

    public void setHeaderView(View headerView) {
        this.headerView = headerView;
    }

    /**
     * 设置headerView的标题
     *
     * @param title
     * @param position
     */
    public void setHeaderTitle(String title, Constants.Position position) {
        TextView tvTitle = (TextView) headerView.findViewById(R.id.tv_header_title);
        switch (position) {
            case LEFT:
                tvTitle.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                break;
            case CENTER:
                tvTitle.setGravity(Gravity.CENTER);
                break;
            case RIGHT:
                tvTitle.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
                break;
        }
        if (title == null) {
            tvTitle.setText("");
        } else {
            tvTitle.setText(title);
        }
    }

    public void setHeaderTitle(String title) {
        setHeaderTitle(title, Constants.Position.CENTER);
    }

    /**
     * 设置headerView左右的图片
     *
     * @param pos         设置左侧还是右侧
     * @param resId       显示的图片的资源ID
     * @param colorFilter 是否需要添加colorFilter
     * @param listener    单击事件监听OnClickListener
     */
    public void setHeaderImage(Constants.Position pos, int resId, boolean colorFilter, View.OnClickListener listener) {
        ImageView iv = null;
        switch (pos) {
            case LEFT:
                iv = (ImageView) headerView.findViewById(R.id.iv_header_left);
                break;

            default:
                iv = (ImageView) headerView.findViewById(R.id.iv_header_right);
                break;
        }
        iv.setImageResource(resId);

        if (colorFilter) {
            iv.setColorFilter(Color.WHITE);
        }

        if (listener != null) {
            iv.setOnClickListener(listener);
        }

    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor() {
        StatusBarSetting.setColor(this, getResources().getColor(R.color.colorPrimary));
    }

    /**
     * 着色状态栏（4.4以上系统有效）
     */
    protected void SetStatusBarColor(int color) {
        StatusBarSetting.setColor(this, color);
    }

    /**
     * 沉浸状态栏（4.4以上系统有效）
     */
    protected void SetTranslanteBar() {
        StatusBarSetting.setTranslucent(this);
    }


    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle,
                                       int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 开启浮动加载进度条
     */
    public void startProgressDialog() {
        count++;
        if (count == 1) {
            LoadingDialog.showDialogForLoading(this);
        }
    }

    /**
     * 开启浮动加载进度条
     */

    public void startProgressDialog(String msg) {
        count++;
        if (count == 1) {
            LoadingDialog.showDialogForLoading(this, msg, true);
        }
    }

    /**
     * 停止浮动加载进度条
     */

    public void stopProgressDialog() {
        count--;
        if (count == 0) {
            LoadingDialog.cancelDialogForLoading();
        }

    }

    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        MyToast.makeText(mContext, text, Toast.LENGTH_SHORT).show();
    }

    /**
     * 短暂显示Toast提示(id)
     **/
    public void showShortToast(int resId) {
        ToastUitl.showShort(resId);
    }

    /**
     * 长时间显示Toast提示(来自res)
     **/
    public void showLongToast(int resId) {
        ToastUitl.showLong(resId);
    }

    /**
     * 长时间显示Toast提示(来自String)
     **/
    public void showLongToast(String text) {
        ToastUitl.showLong(text);
    }

    /**
     * 带图片的toast
     *
     * @param text
     * @param res
     */
    public void showToastWithImg(String text, int res) {
        ToastUitl.showToastWithImg(text, res);
    }

    /**
     * 网络访问错误提醒
     */
  /*  public void showNetErrorTip() {
        ToastUitl.showToastWithImg(getText(R.string.net_error).toString(), R.drawable.ic_wifi_off);
    }

    public void showNetErrorTip(String error) {
        ToastUitl.showToastWithImg(error, R.drawable.ic_wifi_off);
    }*/
    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
        this.imm = null;
        if (mImmersionBar != null) {
            mImmersionBar.destroy();//必须调用该方法，防止内存泄漏，不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
        }
        AppManager.getAppManager().finishActivity(this);
    }

    /**
     * @param rationale   首次申请被用户拒绝后再次申请给用户提示描述
     * @param requestCode 需要申请的权限的数组
     * @param perms       申请标记值
     * @param callback    申请接口
     */
    protected void performCodeWithPermission(@NonNull String rationale,
                                             final int requestCode, @NonNull String[] perms, @NonNull PermissionCallback callback) {
        if (EasyPermissions.hasPermissions(this, perms)) {
            callback.hasPermission(Arrays.asList(perms));
        } else {
            if (mPermissonCallbacks == null) {
                mPermissonCallbacks = new HashMap<>();
            }
            mPermissonCallbacks.put(requestCode, callback);

            if (mPermissions == null) {
                mPermissions = new HashMap<>();
            }
            mPermissions.put(requestCode, perms);

            EasyPermissions.requestPermissions(this, rationale, requestCode, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (mPermissonCallbacks == null || !mPermissonCallbacks.containsKey(requestCode)) {
            return;
        }
        if (mPermissions == null || !mPermissions.containsKey(requestCode)) {
            return;
        }

        // 100% granted permissions
        if (mPermissions.get(requestCode).length == perms.size()) {
            mPermissonCallbacks.get(requestCode).hasPermission(Arrays.asList(mPermissions.get(requestCode)));
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (mPermissonCallbacks == null || !mPermissonCallbacks.containsKey(requestCode)) {
            return;
        }
        if (mPermissions == null || !mPermissions.containsKey(requestCode)) {
            return;
        }

        //granted permission
        List<String> grantedPerms = new ArrayList<>();
        for (String perm : mPermissions.get(requestCode)) {
            if (!perms.contains(perm)) {
                grantedPerms.add(perm);
            }
        }

        //check has permission denied permanently
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            mPermissonCallbacks.get(requestCode).noPermission(perms, grantedPerms, true);
        } else {
            mPermissonCallbacks.get(requestCode).noPermission(perms, grantedPerms, false);
        }
    }

    /**
     * 弹出提醒
     *
     * @param rationale
     */
    protected void alertAppSetPermission(String rationale) {
        new AppSettingsDialog.Builder(this, rationale)
                .setTitle(getString(R.string.title_settings_dialog))
                .setPositiveButton(getString(R.string.setting))
                .setNegativeButton(getString(R.string.cancel), null)
                .build()
                .show();
    }

    /**
     * 弹框提醒
     *
     * @param rationale
     * @param requestCode
     */
    protected void alertAppSetPermission(String rationale, int requestCode) {
        new AppSettingsDialog.Builder(this, rationale)
                .setTitle(getString(R.string.title_settings_dialog))
                .setPositiveButton(getString(R.string.setting))
                .setNegativeButton(getString(R.string.cancel), null)
                .setRequestCode(requestCode)
                .build()
                .show();
    }

    protected interface PermissionCallback {
        /**
         * has all permission
         *
         * @param allPerms
         */
        void hasPermission(List<String> allPerms);

        /**
         * denied some permission
         *
         * @param deniedPerms
         * @param grantedPerms
         * @param hasPermanentlyDenied
         */
        void noPermission(List<String> deniedPerms, List<String> grantedPerms, Boolean hasPermanentlyDenied);
    }

}
